import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
from ..core.tool import Tool, ToolCategory
from ..utils.icons import IconManager


class ToolTree:
    def __init__(self, parent, config, logger):
        self.parent = parent
        self.config = config
        self.logger = logger

        self.frame = ttk.Frame(parent, padding=10)
        self._setup_treeview()
        self._load_data()

    def _setup_treeview(self):
        # 树形组件
        self.tree = ttk.Treeview(self.frame, columns=("status"), show="tree headings")
        self.tree.heading("#0", text="工具列表")
        self.tree.heading("status", text="状态")

        # 图标管理
        self.icons = IconManager()

        # 滚动条
        vsb = ttk.Scrollbar(self.frame, orient="vertical", command=self.tree.yview)
        hsb = ttk.Scrollbar(self.frame, orient="horizontal", command=self.tree.xview)
        self.tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)

        # 布局
        self.tree.grid(row=0, column=0, sticky="nsew")
        vsb.grid(row=0, column=1, sticky="ns")
        hsb.grid(row=1, column=0, sticky="ew")

        # 绑定事件
        self.tree.bind("<Double-1>", self._on_double_click)

    def _load_data(self):
        for category in self.config.data["categories"]:
            parent = self.tree.insert("", "end", text=category["name"], image=self.icons.folder)
            for tool_data in category["tools"]:
                tool = Tool(**tool_data)
                self.tree.insert(
                    parent, "end",
                    text=tool.name,
                    values=("stopped"),
                    image=self.icons.get_icon(tool.icon),
                    tags=(tool.name,)
                )

    def _on_double_click(self, event):
        item = self.tree.selection()[0]
        tool_name = self.tree.item(item, "text")
        self.logger.info(f"启动工具: {tool_name}")